<template>
   <el-card>
      <template #header>
         <el-button type="primary" :icon="Plus" @click="dialogVisible = true">添加</el-button>
      </template>
      <el-table border style="width: 100%" :data="trademarkInfo" class="mb-10">
         <el-table-column label="序号" type="index" width="100" align="center" />
         <el-table-column prop="tmName" label="品牌名称" align="center" />
         <el-table-column prop="logoUrl" label="品牌LOGO" align="center">
            <!-- <template #default="scope"> -->
            <template #default="{ $index, row }">
               <img :src="row.logoUrl" style="width:100px;height: 100px;">
            </template>
         </el-table-column>
         <el-table-column label="操作" align="center">
            <template #default="scope">
               <el-button size="small" type="warning" :icon="Edit" @click="handleEdit(scope.$index, scope.row)">编辑
               </el-button>
               <el-button size="small" type="danger" :icon="Delete" @click="handleDelete(scope.$index, scope.row)">删除
               </el-button>
            </template>
         </el-table-column>>
      </el-table>
      <el-pagination v-model:currentPage="page" v-model:page-size="limit" @size-change="handleSizeChange"
         @current-change="handleCurrentChange" :page-sizes="[3, 6, 9]"
         layout=" prev, pager, next, jumper,->, sizes,total" :total="total" />


      <el-dialog v-model="dialogVisible" :title="title"
      :close-on-click-modal="false"
       :show-close="false" 
      :close-on-press-escape="false">
         <el-form :model="addForm" ref="ruleFormRef" :rules="rules">
            <el-form-item label="品牌名称" :label-width="100" prop="tmName" style="width: 500px;">
               <el-input v-model="addForm.tmName" />
            </el-form-item>
            <el-form-item label="品牌LOGO" :label-width="100" prop="logoUrl">
               <el-upload class="avatar-uploader" action="/app-dev/admin/product/upload" :show-file-list="false"
                  :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                  <img v-if="addForm.logoUrl" :src="addForm.logoUrl" class="avatar" />
                  <el-icon v-else class="avatar-uploader-icon">
                     <Plus />
                  </el-icon>
                  <template #tip>
                     <div class="el-upload__tip">
                        上传图片必须是jpg且不能大于2M
                     </div>
                  </template>
               </el-upload>
            </el-form-item>
         </el-form>
         <template #footer>
            <span class="dialog-footer">
               <el-button @click="onCancelSave(ruleFormRef)">取消</el-button>
               <el-button type="primary" @click="onSave(ruleFormRef)">保存</el-button>
            </span>
         </template>
      </el-dialog>
   </el-card>
</template>

<script setup lang="ts">

import { Plus, Delete, Edit, } from '@element-plus/icons-vue';
import type { UploadProps, FormInstance, FormRules } from 'element-plus'
import trademark, { type TradeMarkModel } from "@/api/trademark";
import { onMounted, ref, reactive ,computed } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import {cloneDeep} from "lodash";
// 当前页码与每页的条数
const page = ref(1);
const limit = ref(3);
const total = ref(0);
// const id=ref(null);
const trademarkInfo = ref<TradeMarkModel[]>();
//获取数据
onMounted(() => {
   getPage()
})
const getPage = async () => {
   try {
      let result = await trademark.getPage(page.value, limit.value);
      // console.log(result);
      trademarkInfo.value = result.records;
      total.value = result.total;
   } catch (err) {
      console.log("getpageErr", err);
      return Promise.reject(err)
   }
};
const handleEdit = (index: number, row: TradeMarkModel) => {
   // console.log(index, row)
   //弹出框
   //将该行信息传到表单中
   addForm.value =cloneDeep(row) ;
   dialogVisible.value = true;


}
// const handleDelete = async (index: number, row: TradeMarkModel) => {
//    // console.log(index, row);
//    try{
//       let result=await trademark.delete(row.id as number);
//       // console.log(result);
//       console.log("删除成功");
//       getPage();
//       ElMessage.success("删除成功");
//    }catch(err){
//       console.log("删除该条数据失败",err)
//       return Promise.reject(err)
//    }
// }
const handleDelete = async (index: number, row: TradeMarkModel) => {
  try {
    const res =  await ElMessageBox.confirm(
      `确认要删除[${ row.tmName }]吗?`,
      '警告',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    if (trademarkInfo.value?.length == 1 && page.value != 1) {
      page.value -= 1;
    }
    await trademark.delete(row.id as number); 
    ElMessage.success('删除成功'); 
    getPage(); 
  } catch (error) {}
}

const handleSizeChange = (val: number) => {
   //   console.log(`${val} 是每页条数`);
   limit.value = val;
   getPage()
}
const handleCurrentChange = (val: number) => {
   //   console.log(`当前页: ${val}`);
   page.value = val;
   getPage();
}

//添加数据弹框
const dialogVisible = ref(false);
const addForm = ref<TradeMarkModel>({
   tmName: '',
   logoUrl: '',
   id:undefined

});
const onCancelSave = (formEl: FormInstance | undefined) => {
   if (!formEl) return
   //去除校验
   formEl?.resetFields();
   addForm.value = { tmName: '', logoUrl: '' }; 
   dialogVisible.value = false;

  
};
// 有问题版
// const onSave = async (formEl: FormInstance | undefined) => {

//    if (!formEl) return
//    await formEl.validate(async (valid, fields) => {
//       if (valid) {
//         try{
//           console.log('校验成功',addForm.value);
//          let result= await trademark.add(addForm.value);
//          // console.log(result);
//          dialogVisible.value = false;

//         }catch(err){
//           return Promise.reject(err);
//         }
//          formEl.resetFields()
//       } else {
//          console.log('校验失败', fields);
//           formEl.resetFields()
//       }
//    });

// }
//添加操作
// const onSave = (formEl: FormInstance | undefined) => {
//    if (!formEl) return
//    formEl.validate(async (valid) => {
//       if (valid) {
//          console.log('submit!');
//          try {
//             let result = await trademark.add(addForm.value);
//             // console.log(result)
//             console.log("添加成功");
//              formEl.resetFields()
//             dialogVisible.value = false;
//          } catch (err) {
//             console.log("添加失败");
//              formEl.resetFields()
//             return Promise.reject(err)
//          }

//       } else {
//           console.log('error submit!');
//          //  formEl.resetFields();
//           ElMessage.error('请确认提交的内容不为空')
//           return false
//       }
//    })
// }
const title=computed(()=>{
   return addForm.value.id?'修改品牌':'添加品牌'
})

const onSave = (formEl: FormInstance | undefined) => {
   // console.log(formEl)
   if (!formEl) return
   formEl.validate(async (valid) => {
      if (valid) {
         console.log('submit!');
         if (addForm.value.id) {
            try {
               let result = await trademark.update(addForm.value);
               // console.log(result)
               console.log("修改成功");
               dialogVisible.value = false;
               ElMessage.success('修改成功')
            } catch (err) {
               console.log("修改失败");
               formEl.resetFields()
               return Promise.reject(err)
            }
         } else {
            //添加逻辑
            try {
               let result = await trademark.add(addForm.value);
               // console.log(result)
               console.log("添加成功");
               formEl.resetFields()
               dialogVisible.value = false;
                 ElMessage.success('添加成功')
            } catch (err) {
               console.log("添加失败");
               formEl.resetFields()
               return Promise.reject(err)
            }
         }





      } else {
         console.log('error submit!');
         //  formEl.resetFields();
         ElMessage.error('请确认提交的内容不为空')
         return false
      }
   })
}

// const handleClose = (done: () => void) => {
//    dialogVisible.value = false;
  
//    // ElMessageBox.confirm('确认不保存该信息吗?')
//    //    .then(() => {
//    //       done()
//    //    })
//    //    .catch(() => {
//    //       // catch error
//    //    })
// }

const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
   // console.log('response',response)
   // console.log('uploadFile',uploadFile)

   // console.log(uploadFile.raw!)
   // console.log(URL.createObjectURL)
   addForm.value.logoUrl = URL.createObjectURL(uploadFile.raw!)
   // addForm.value.logoUrl = response.data;
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
   if (rawFile.type !== 'image/jpeg') {
      ElMessage.error('图片格式必须是 JPG !')
      return false
   } else if (rawFile.size / 1024 / 1024 > 2) {
      ElMessage.error('图片大小不能超过 2MB!')
      return false
   }
   return true
}

//校验
const ruleFormRef = ref<FormInstance>();


const rules = reactive<FormRules>({
   tmName: [
      { required: true, message: '品牌名称是必须的', trigger: 'blur' },
      { min: 2, message: '品牌名称不少于2个字符', trigger: 'blur' },
   ],
   logoUrl: [
      {
         required: true,
         message: '品牌图片必须上传',
         trigger: 'change',
      },
   ],
})

</script>

<style scoped>
</style>
<style scoped>
.dialog-footer button:first-child {
   margin-right: 10px;
}
</style>
<style scoped>
.avatar-uploader .avatar {
   width: 178px;
   height: 178px;
   display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
   border: 1px dashed var(--el-border-color);
   border-radius: 6px;
   cursor: pointer;
   position: relative;
   overflow: hidden;
   transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
   border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
   font-size: 28px;
   color: #8c939d;
   width: 178px;
   height: 178px;
   text-align: center;
}
</style>
<style>
.el-dialog {
   margin-top: 120px;

}
</style>